import React, { useRef, useState } from "react";
import { Space, Button, message, Modal } from "antd";
import { roleTypes } from "@/constants/types";
import { useRequest } from "ahooks";
import { ProColumnType, ProTable } from "@ant-design/pro-components";
import { fetchRoleList, addRole, updateRole, deleteRole } from '../services';
import RoleUpdateModal from "../modals/RoleUpdateModal";

const RoleManage = () => {
  const tableRef = useRef();
  const {loading: addLoading, runAsync: addApi} = useRequest(addRole, {manual: true});
  const {loading: updateLoading, runAsync: updateApi} = useRequest(updateRole, {manual: true});

  const [currentRow, setCurrentRow] = useState<roleTypes | null>(null);
  const [disabled, setDisabled] = useState(false);
  const [visible, setVisible] = useState<boolean>(false);

  const roleUpdateProps = {
    title: currentRow ? (disabled ? '查看角色' : '编辑角色' ) : '新增角色',
    visible,
    disabled,
    loading: addLoading || updateLoading,
    currentRow,
    onSubmit: async (params: roleTypes) => {
      const apiFunc = currentRow ? updateApi : addApi;
      const res = await apiFunc(currentRow ? {
        ...params, 
        id: currentRow?.id
      } : params);
      if (res.code === '0') {
        message.success('操作成功');
        roleUpdateProps.onCancel();
        tableRef?.current?.reload();
      }
    },
    onCancel: () => {
      setVisible(false);
      setDisabled(false);
      setCurrentRow(null);
    }
  }

  const handleAdd = () => {
    setVisible(true);
  }
  const handleEdit = (record: roleTypes) => {
    setCurrentRow(record);
    setVisible(true);
  }
  const handleView = (record: roleTypes) => {
    setCurrentRow(record);
    setDisabled(true);
    setVisible(true);
  }
  const handleDelete = (record: roleTypes) => {
    Modal.confirm({
      title: '是否确定删除此角色？',
      onOk: () => {
        deleteRole({id: record?.id}).then(res => {
          if (res?.code === '0') {
            message.success(res?.msg || '删除成功!');
            tableRef?.current?.reload();
          }
        })
      }
    });
  }

  const columns: ProColumnType<roleTypes>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      render: (_: any, record: roleTypes, index: number) => <span>{ String(index + 1)}</span>
    },
    { 
      title: '角色',
      dataIndex: 'roleName',
    },
    { 
      title: '描述',
      dataIndex: 'remark',
    },
    { 
      title: '创建时间',
      dataIndex: 'createTime',
    },
    { 
      title: '创建人',
      dataIndex: 'createBy',
    },
    { 
      title: '操作人',
      dataIndex: 'options',
      width: 250,
      render: (_, record: roleTypes) => {
        return (
          <Space>
            <Button type="link" onClick={() => handleView(record)}>查看权限</Button>
            <Button type="link" onClick={() => handleEdit(record)}>编辑</Button>
            <Button type="link" onClick={() => handleDelete(record)}>删除</Button>
          </Space>
        );
      }
    },
  ];

  return (
    <>
      <ProTable
        bordered
        actionRef={tableRef}
        search={false}
        rowKey="id"
        className="xl-no-search-protable"
        columns={columns}
        options={false}
        toolBarRender={() => [
          <Button type="primary" key="addRole" onClick={handleAdd}>新建角色</Button>
        ]}
        request={async (params) => {
          const res = await fetchRoleList({
            pageNum: params.current || 1,
            pageSize: params.pageSize || 20
          });
          const { data, total } = res || {};
          return {
            data: data || [],
            success: true,
            total: total || 0
          }
        }}
      />
      {visible && <RoleUpdateModal {...roleUpdateProps} />}
    </>
  );
}
export default RoleManage;